<?php

class Application_Model_UtilisateurMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Utilisateur');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Utilisateur $user)
	{
		$data = array(
				'login'   		=> $user->getLogin(),
				'mdp' 			=> $user->getMdp(),
				'salt'			=> $user->getSalt(),
				'nomutil' 		=> $user->getNom(),
				'prenomutil' 	=> $user->getPrenom(),
				'adresseutil'   => $user->getAdresse(),
				'cputil'   		=> $user->getCp(),
				'villeutil'   	=> $user->getVille(),
				'telephoneutil' => $user->getTelephone(),
				'emailutil'  	=> $user->getEmail(),
				'noteutil'   	=> $user->getNote(),
		);
	
		if (null === ($id = $user->getId())) {
			unset($data['idutilisateur']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('idutilisateur = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Utilisateur $user)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$user->setId($row->idutilisateur)
			->setLogin($row->login)
			->setNom($row->nomutil)
			->setPrenom($row->prenomutil)
			->setAdresse($row->adresseutil)
			->setCp($row->cputil)
			->setVille($row->villeutil)
			->setTelephone($row->telephoneutil)
			->setEmail($row->emailutil)
			->setNote($row->noteutil);
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Utilisateur();
			$entry->setId($row->idutilisateur)
				->setLogin($row->login)
				->setNom($row->nomutil)
				->setPrenom($row->prenomutil)
				->setAdresse($row->adresseutil)
				->setCp($row->cputil)
				->setVille($row->villeutil)
				->setTelephone($row->telephoneutil)
				->setEmail($row->emailutil)
				->setNote($row->noteutil);
			$entries[] = $entry;
		}
		return $entries;
	}

}

